/*
Copyright (c) 2009, Heinrich C. Spreiter
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  - Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
  
  - Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
  
  - Neither the name of the author nor the names of its contributors may be used
  to endorse or promote products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ch.kynlang.compiler.symbol;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.antlr.runtime.tree.Tree;

import ch.kynlang.compiler.EvaluationException;
import ch.kynlang.compiler.KohYaoNoiError;
import ch.kynlang.compiler.KohYaoNoiLexer;
import ch.kynlang.compiler.scope.IScope;
import ch.kynlang.compiler.scope.RootScope;
import ch.kynlang.compiler.tree.KynTree;

/*
 * SymbolTable.java
 *
 * @version 0.1 27.12.2009
 * @author HSP spreiter301@gmail.com
 * 
 * The symbol table holds all informations during compiling.
 * It also provides helper methods
 */
public class SymbolTable {
	public RootScope rootScope = null;
	
	// list of all errors
	public List<KohYaoNoiError> errors = null;
	public SymbolTable() {
		this.rootScope = new RootScope();
		this.errors = new LinkedList<KohYaoNoiError>();
	}
	
	/**
	 * adds a new error to the list
	 * @param error error to add
	 */
	public void error(KohYaoNoiError error) {
		errors.add(error);
	}
	
	public static Class<?> evaluate(KynTree tree, IScope scope, StringBuilder sb) throws EvaluationException {
		Class<?> clazz = null;
		String symbolName = null;
		Symbol symbol = null;
		switch(tree.getType()) {
			case KohYaoNoiLexer.STRINGLITERAL:
				clazz = String.class;
				sb.append(tree.getText());
				break;
			case KohYaoNoiLexer.INTEGER:
				if(tree.getText().endsWith("l") || tree.getText().endsWith("L")) {
					clazz = long.class;
				} else {
					clazz = int.class;
				}
				sb.append(tree.getText());
				break;
			case KohYaoNoiLexer.FLOAT:
				if(tree.getText().endsWith("f") || tree.getText().endsWith("F")) {
					clazz = float.class;
				} else {
					clazz = double.class;
				}
				sb.append(tree.getText());
				break;
			case KohYaoNoiLexer.CHARACTERLITERAL:
				clazz = char.class;
				sb.append(tree.getText());
				break;
			case KohYaoNoiLexer.BOOL:
				clazz = boolean.class;
				sb.append(tree.getChild(0).getText());
				break;
			case KohYaoNoiLexer.NEW:
				// first check if class is defined in this scope
				symbolName = tree.getChild(0).getText();
				symbol = scope.resolve(symbolName);
				if(symbol == null || symbol.type.getTypeNumber() != KohYaoNoiLexer.IMPORT) {
					// class not defined!
					throw new EvaluationException(tree, "Class " + symbolName + " not found");
				}
				sb.append("new ");
				sb.append(symbol.type.getFullQualifiedName());
				sb.append("(");
				clazz = symbol.type.getJavaClass();
				Class<?>[] args = new Class<?>[0];
				// check argument classes
				if(tree.getChildCount() > 1) {
					KynTree argList = (KynTree) tree.getChild(1);
					args = new Class<?>[argList.getChildCount()];
					
					for(int i = 0; i < args.length; i++) {
						args[i] = evaluate((KynTree) argList.getChild(i), scope, sb);
						if(i < args.length - 1) {
							sb.append(", ");
						}
					}
				}
				sb.append(")");
				try {
					clazz.getConstructor(args);
				} catch(Exception e) {
					StringBuilder argsb = new StringBuilder();
					for(int i = 0; i < args.length; i++) {
						argsb.append(args[i].getName());
						if(i < args.length - 1) {
							argsb.append(", ");
						}
					}
					throw new EvaluationException(tree, "Constructor " + argsb + " for " + symbolName + " not found");
				}
				break;
				// end KohYaoNoiLexer.NEW
			case KohYaoNoiLexer.VARACC:
				// find symbol
				symbolName = tree.getChild(0).getText();
				symbol = scope.resolve(symbolName);
				
				if(symbol == null || (symbol.type.getTypeNumber() != KohYaoNoiLexer.IMPORT &&
										symbol.type.getTypeNumber() != KohYaoNoiLexer.DEF)) {
					throw new EvaluationException(tree, "Variable " + symbolName + " not found");
				}
				// 1 child = end of search
				if(tree.getChildCount() == 1) {
					// can only be a variable DEF
					// IMPORT (static) not allowed
					if(symbol.type.getTypeNumber() == KohYaoNoiLexer.IMPORT) {
						throw new EvaluationException(tree, "Access of import " + symbolName + " not allowed");
					}
					
					clazz = symbol.type.getJavaClass();
					sb.append(symbolName); // variable name
				} else {
					// evaluate children
					ArrayList<Tree> children = new ArrayList<Tree>();
					Tree currentTree = tree;
					
					while(currentTree != null) {
						children.add(currentTree);
						
						// check for more access
						switch(currentTree.getType()) {
							case KohYaoNoiLexer.VARACC:
								if(currentTree.getChildCount() == 1) {
									currentTree = null;
								} else {
									currentTree = currentTree.getChild(1);
								}
								break;
							case KohYaoNoiLexer.METACC:
								Tree lastChild = currentTree.getChild(currentTree.getChildCount() - 1);
								switch(lastChild.getType()) {
									case KohYaoNoiLexer.VARACC:
									case KohYaoNoiLexer.METACC:
										currentTree = lastChild;
										break;
									default:
										// exit
										currentTree = null;
										break;
								}
								break;
						}
					}
					
					// evaluate based on java class
					clazz = symbol.type.getJavaClass();
					if(symbol.type.getTypeNumber() == KohYaoNoiLexer.IMPORT) {
						sb.append(symbol.type.getFullQualifiedName());
					} else {
						sb.append(symbolName);
					}
					for(int i = 1; i < children.size(); i++) {
						currentTree = children.get(i);
						switch(currentTree.getType()) {
							case KohYaoNoiLexer.VARACC:
								// check if valid property
							try {
								Field field = clazz.getField(currentTree.getChild(0).getText());
								if(i == 1 && symbol.type.getTypeNumber() == KohYaoNoiLexer.IMPORT) {
									// check for non static access on imports
									boolean isStatic = Modifier.isStatic(field.getModifiers());
									if(!isStatic) {
										// non static access!
										throw new EvaluationException((KynTree) currentTree.getChild(0), "Non static property access on import: " + currentTree.getChild(0).getText());
									}
								}
								clazz = field.getType();
								sb.append(".");
								sb.append(field.getName());
								
							} catch(EvaluationException e) {
								throw e;
							} catch (Exception e) {
								throw new EvaluationException((KynTree) currentTree.getChild(0), "Invalid property " + currentTree.getChild(0).getText());
							}
								break;
							case KohYaoNoiLexer.METACC:
								sb.append(".");
								sb.append(currentTree.getChild(0).getText());
								sb.append("(");
								args = new Class<?>[0];
								// check argument classes
								if(currentTree.getChildCount() > 1) {
									KynTree argList = (KynTree) currentTree.getChild(1);
									args = new Class<?>[argList.getChildCount()];
									
									for(int j = 0; j < args.length; j++) {
										args[j] = evaluate((KynTree) argList.getChild(j), scope, sb);
										if(j < args.length - 1) {
											sb.append(", ");
										}
									}
								}
								sb.append(")");
								
							try {
								Method method = clazz.getMethod(currentTree.getChild(0).getText(), args);
								if(i == 1 && symbol.type.getTypeNumber() == KohYaoNoiLexer.IMPORT) {
									// check for non static access on imports
									boolean isStatic = Modifier.isStatic(method.getModifiers());
									if(!isStatic) {
										// non static access!
										throw new EvaluationException((KynTree) currentTree.getChild(0), "Non static method access on import: " + currentTree.getChild(0).getText());
									}
								}
								clazz = method.getReturnType();
								
							} catch(EvaluationException e) {
								throw e;
							} catch (Exception e) {
								StringBuilder argsb = new StringBuilder();
								for(int j = 0; j < args.length; j++) {
									argsb.append(args[j].getName());
									if(i < args.length - 1) {
										argsb.append(", ");
									}
								}
								throw new EvaluationException((KynTree) currentTree, "Method " + currentTree.getChild(0).getText() + "(" + argsb + ") not found");
							}
								break;
						}
					}
				}
				
				break;
		}
		
		return clazz;
	}
	
}

